#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("TCP - 服务器接收文件");
    //创建QTcpServer对象
    m_server = new QTcpServer(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_startServer_clicked()
{
    unsigned short port = ui->port->text().toInt();
    //设置服务器监听
    m_server->listen(QHostAddress::LocalHost,port);

    //检测是否有新链接
    connect(m_server,&QTcpServer::newConnection,this,[&]()
            {
                m_tcp = m_server->nextPendingConnection(); //获取TCP连接
                ui->m_status->setText("已连接");
                //客户端发送过来了数据
                connect(m_tcp,&QTcpSocket::readyRead,this,[&]()
                        {
                            //读取数据
                            QByteArray array = m_tcp->readAll();
                            if(headinfo)
                            {
                                headinfo = false;
                                recvsize = 0;
                                filename = QString(array).section("**",0,0); //起始，结束
                                filesize = QString(array).section("**",1,1).toInt();

                                file.setFileName(filename); //设置文件

                                file.open(QIODevice::WriteOnly);//只读的方式打开文件
                                //设置传输的进度条
                                ui->progressBar->setMinimum(0);
                                ui->progressBar->setMaximum(filesize / 1024);
                                ui->progressBar->setValue(0);  //设置当前值为0

                            }
                            else
                            {
                                //处理数据文件
                                qint64 length = file.write(array);
                                if(length > 0)
                                {
                                    recvsize +=length;
                                }
                                ui->progressBar->setValue(recvsize / 1024);
                                qDebug() <<"接收大小"<< recvsize <<"文件大小"<< filesize;
                                if(recvsize == filesize)
                                {

                                    QMessageBox::information(this,"完成","文件接受完成");
                                    file.close();
                                }

                            }

                        });
            });

}

